<template>
    <div>
        <div class="flexDict">
            <div class="flex-right">
                <div class="flex-right-item">
                    <navigationBarCustom customTitle="字典标识">
                        <div class="searchContent">
                            <el-input
                                v-model="username"
                                placeholder="请输入字典名称"
                                size="mini"
                                style="width: 150px; margin-right: 10px"
                            ></el-input>
                            <custom-button type="add" @addClick="addTableClick"></custom-button>
                        </div>
                    </navigationBarCustom>
                    <div style="margin-top: 10px" class="firstTableDict">
                        <tableIndex
                            :dataSource="dataSource"
                            :tableColumns="tableColumns"
                            :btnList="btnList"
                            :pageSize="pageSize"
                            :pageCount="pageCount"
                            :pageNo="pageNo"
                            @pageChange="pageChange"
                            @editRow="editTableRow"
                            @viewRow="viewRow"
                            @handleSizeChange="handleSizeChange"
                            @deleteRow="deleteTableRow"
                            selection
                            height="340"
                            @handleSelectionChange="handleTableSelectionChange"
                            @handleCurrentChange="handleCurrentChange"
                        ></tableIndex>
                    </div>
                </div>
                <div class="flex-right-item" style="margin-top: 53px">
                    <navigationBarCustom customTitle="字典值">
                        <div class="searchContent">
                            <custom-button type="add" @addClick="addClick"></custom-button>
                        </div>
                    </navigationBarCustom>
                    <tableIndex
                        :dataSource="dataSourceDown"
                        :tableColumns="tableColumnsDown"
                        :btnList="btnListDown"
                        :pageSize="pageSizeDown"
                        :pageCount="pageCountDown"
                        :pageNo="pageNoDown"
                        @editRow="editRow"
                        @viewRow="viewRow"
                        @deleteRow="deleteRow"
                        :height="secondTableHeight"
                    ></tableIndex>
                </div>
            </div>
        </div>
        <div v-if="dialogShow">
            <custom-dialog :title="dialogTitle" size="large" @dialogClose="dialogClose">
                <form-index :formConfig="formConfig" @submit="tableSubmit2" :type="type" @formInputChange="formInputChange" ref="form">
                </form-index>
            </custom-dialog>
        </div>

        <!-- 字典标识 -->
        <div v-if="dialogTableShow">
            <custom-dialog :title="dialogTableTitle" size="large" @dialogClose="dialogTableClose">
                <form-index
                    :formConfig="formTableConfig"
                    @submit="tableSubmit"
                    :type="tableType"
                    @formInputChange="formInputChange"
                    ref="form"
                >
                </form-index>
            </custom-dialog>
        </div>
    </div>
</template>

<script>
import {dictManageForm} from '@/assets/form/managementCenter/systemManage/dictManage.js'
import {dictValueManageForm} from '@/assets/form/managementCenter/systemManage/dictValueManage.js'
import customDialog from '@/components/customComponents/customDialog'
import customButton from '@/components/customComponents/customForm/customButton'
import formIndex from '@/components/customComponents/customForm/formIndex'
import tableIndex from '@/components/customComponents/customeTable/iviewTable/singleViewTable'
import navigationBarCustom from '@/components/customComponents/managementCenter/navigationBarCustom.vue'
import {AjaxCommon} from '@/libs/apiCommon'
import {PopupCommon} from '@/libs/popupCommon'
import {SessionCommon} from '@/libs/sessionCommon'
// import {Utility} from "@/libs/utility"
export default {
    components: {
        navigationBarCustom,
        customButton,
        customDialog,
        formIndex,
        tableIndex
    },
    data() {
        return {
            inter: null,
            customTitle: '岗位维护',
            defaultProps: {
                children: 'children',
                label: 'label'
            },
            tableColumnsDown: [
                {
                    type: 'index',
                    width: 60,
                    align: 'center'
                },
                {
                    key: 'value',
                    title: '字典值'
                },
                {
                    key: 'desc',
                    title: '说明'
                },
                {
                    key: 'enable',
                    title: '是否启用',
                    slot: 'enable'
                },
                {
                    title: '操作',
                    slot: 'action',
                    width: 120,
                    align: 'center'
                }
            ],
            dataSourceDown: [],
            dialogTableShow: false,
            dialogTableTitle: '新增字典',
            curHeight: 100,
            data: [],
            yzId: '',
            secondTableHeight: document.body.clientHeight - 610,
            selectTableItem: [],
            tableItem: {},
            selectItem: [],
            username: '',
            // table 相关参数  begin
            dataSource: [],
            tableColumns: [
                // {
                //     type: 'selection',
                //     width: 60,
                //     align: 'center'
                // },
                {
                    type: 'index',
                    width: 60,
                    align: 'center'
                },
                {
                    key: 'type_name',
                    title: '分类名称'
                },
                {
                    key: 'type_tag',
                    title: '分类标识'
                },
                {
                    key: 'type_alias',
                    title: '分类别名'
                },
                {
                    key: 'type_desc',
                    title: '分类说明'
                },
                {
                    title: '操作',
                    slot: 'action',
                    width: 120,
                    align: 'center'
                }
            ],
            btnList: ['edit', 'delete'],
            btnListDown: ['edit', 'delete'],
            pageSize: 20,
            pageCount: 1,
            pageNo: 1,

            pageSizeDown: 20,
            pageCountDown: 1,
            pageNoDown: 1,
            // table 相关参数  end

            // 弹窗是否显示
            dialogShow: false,
            // 弹窗标题 (新增修改不同)
            dialogTitle: '',

            // form的配置信息
            formConfig: dictValueManageForm,
            type: 'add',

            formTableConfig: dictManageForm,
            tableType: 'add'
        }
    },
    methods: {
        handleSizeChange(e) {
            this.pageSize = e
            this.pageNo = 1
            this.initPage()
        },
        dialogTableClose() {
            this.dialogTableShow = false
        },
        getHeight() {
            this.secondTableHeight = document.body.clientHeight - 610
        },
        addTableClick() {
            this.tableItem = {}

            let formConfigItem = this.formTableConfig
            formConfigItem.map((t) => {
                Object.keys(t).map((res) => {
                    if (res == 'fieldName') {
                        t.filedValue = ''
                    }
                })
            })
            this.formTableConfig = formConfigItem
            this.tableType = 'add'
            this.dialogTableShow = true
            this.dialogTableTitle = '新增字典'
        },
        addClick() {
            if (typeof this.tableItem.type_tag == 'undefined') {
                PopupCommon.notify('info', '请点击分类列表的一行进行选择')
                return
            }

            let formConfigItem = this.formConfig
            formConfigItem.map((t) => {
                Object.keys(t).map((res) => {
                    if (res == 'fieldName') {
                        t.filedValue = ''
                    }
                })
            })
            this.formConfig = formConfigItem

            this.type = 'add'
            this.dialogShow = true
            this.dialogTitle = '（ 分类：【' + this.tableItem.type_name + '】）'
        },
        tableClick(item) {
            this.tableIndex = item.Id
            this.tableItem = {}
            this.dataSourceDown = []
            this.initPage()
        },
        deleteAll() {
            if (this.selectItem.length == 0) {
                PopupCommon.notify('info', '请先勾选数据')
                return
            }
            PopupCommon.notify('success', '删除成功')
            // let self = this
            // PopupCommon.confirm("此操作将删除选择的数据, 是否继续?")
            //     .then(() => {
            //         self.selectItem.forEach((d) => {
            //             const id = d.RelationId
            //             AjaxCommon("/api/TableFieldRelation/Delete?id=" + id, "delete", {
            //                 optReason: ""
            //             }).then((res) => {
            //                 console.log(res)
            //             })
            //         })

            //         setTimeout(() => {
            //             PopupCommon.notify("success", "删除成功")
            //             self.initDownYzzd()
            //         }, 500)
            //     })
            //     .catch(() => {
            //         // 这里尽量写下，否则会报警告异常。
            //         console.log("已取消删除")
            //     })
        },
        deleteTableAll() {
            this.tableItem = {}
            if (this.selectTableItem.length == 0) {
                PopupCommon.notify('info', '请先勾选数据')
                return
            }
            // let self = this
            PopupCommon.notify('success', '删除成功')
            // PopupCommon.confirm("此操作将删除选择的数据, 是否继续?")
            //     .then(() => {
            //         self.selectTableItem.forEach((d) => {
            //             const id = d.Id
            //             AjaxCommon("/api/table/Delete?id=" + id, "delete", {
            //                 optReason: ""
            //             }).then((res) => {
            //                 console.log(res, "res................................")
            //             })
            //         })
            //         setTimeout(() => {
            //             PopupCommon.notify("success", "删除成功")
            //             self.initPage()
            //         }, 500)
            //     })
            //     .catch(() => {
            //         // 这里尽量写下，否则会报警告异常。
            //         console.log("已取消删除")
            //     })
        },

        handleSelectionChange(d) {
            this.selectItem = d
            console.log(d)
        },
        handleTableSelectionChange(d) {
            console.log(d, 'd.........................')
            this.selectTableItem = d
        },
        // 单击行
        handleCurrentChange(d) {
            this.tableItem = d
            this.initDownYzzd()
        },
        formInputChange(e) {
            // if (e.filedName == "idCard") {
            // 	const data = CardId.getInfoByCardId(e.value)
            // 	if (data) {
            // 		let newData = e.allData
            // 		newData["birthday"] = data.birthday
            // 		newData["sex"] = data.sex
            // 		this.$refs.form.changeFormValue(newData)
            // 	}
            // }
            console.log(e)
        },
        tableSubmit(d) {
            const self = this
            if (d.DIC_GUID) {
                delete d.DIC_GUID
                AjaxCommon('/api/Dictionary/EditType', 'post', d).then((res) => {
                    if (res?.data?.Code == 200) {
                        PopupCommon.notify('success', '编辑成功')
                        self.initPage()
                        self.dialogTableClose()
                    } else {
                        const msg = res?.data?.Message
                        if (msg) {
                            PopupCommon.notify('error', msg)
                        }
                    }
                })
            } else {
                delete d.DIC_GUID
                AjaxCommon('/api/Dictionary/AddType', 'post', d).then((res) => {
                    if (res?.data?.Code == 200) {
                        PopupCommon.notify('success', '新增成功')
                        self.initPage()
                        self.dialogTableClose()
                    } else {
                        const msg = res?.data?.Message
                        if (msg) {
                            PopupCommon.notify('error', msg)
                        }
                    }
                })
            }
        },
        tableSubmit2(d) {
            console.log(d, this.tableItem, 'd.....')
            const type = this.tableItem.type_tag
            d.TYPE_TAG = type
            d.IS_ENABLE = d.IS_ENABLE ? 1 : 0
            //  R_ITEM 设备协议关联字段，仅在字典表选SBSCCJ时生效有数据
            d.R_ITEM = ''
            const self = this
            if (d.DIC_GUID) {
                AjaxCommon('/api/Dictionary/EditData', 'post', d).then((res) => {
                    if (res?.data?.Code == 200) {
                        PopupCommon.notify('success', '编辑成功')
                        self.initDownYzzd()
                        self.dialogShow = false
                    } else {
                        const msg = res?.data?.Message
                        if (msg) {
                            PopupCommon.notify('error', msg)
                        }
                    }
                })
            } else {
                delete d.DIC_GUID
                AjaxCommon('/api/Dictionary/AddData', 'post', d).then((res) => {
                    if (res?.data?.Code == 200) {
                        PopupCommon.notify('success', '新增成功')
                        self.initDownYzzd()
                        self.dialogShow = false
                    } else {
                        const msg = res?.data?.Message
                        if (msg) {
                            PopupCommon.notify('error', msg)
                        }
                    }
                })
            }
        },
        dialogClose() {
            this.yzzdSelect = this.yzzdFixedSelect
            this.dialogShow = false
        },
        searchClick() {
            this.pageNo = 1
            this.initPage()
        },
        searchTableClick() {
            this.tableItem = {}
            this.pageNo = 1
            this.initPage()
        },

        resetClick() {
            this.username = ''
        },
        // 分页点击事件
        pageChange(p) {
            this.pageNo = p
            this.initPage()
        },
        editRow(d) {
            this.type = 'edit'
            let formConfigItem = this.formConfig
            formConfigItem.map((t) => {
                Object.keys(t).map((res) => {
                    if (t.fieldName == 'DIC_GUID') {
                        t.filedValue = d['id']
                    } else if (t.fieldName == 'DIC_VALUE') {
                        t.filedValue = d['value']
                    } else if (t.fieldName == 'DIC_DESC') {
                        t.filedValue = d['desc']
                    } else if (t.fieldName == 'IS_ENABLE') {
                        t.filedValue = d['enable'] == '1'
                    }
                })
            })
            this.formConfig = formConfigItem
            this.dialogShow = true
            this.dialogTitle = '编辑岗位'
        },
        editTableRow(d) {
            let formConfigItem = this.formTableConfig
            formConfigItem.map((t) => {
                Object.keys(t).map((res) => {
                    if (res == 'fieldName') {
                        console.log(t.fieldName, 't.fieldName.....')
                        if (t.fieldName == 'DIC_GUID') {
                            t.filedValue = d[t[res]]
                        } else {
                            t.filedValue = d[t[res].toLowerCase()]
                        }
                    }
                })
            })
            this.formTableConfig = formConfigItem
            this.tableType = 'edit'
            this.dialogTableShow = true
            this.dialogTableTitle = '编辑字典'
        },
        viewRow(d) {
            this.type = 'look'
            let formConfigItem = this.formConfig
            formConfigItem.map((t) => {
                Object.keys(t).map((res) => {
                    if (res == 'fieldName') {
                        t.filedValue = d[t[res]]
                    }
                })
            })
            this.formConfig = formConfigItem
            this.dialogShow = true
            this.dialogTitle = '查看' + JSON.parse(SessionCommon.getCurrentMenuInfo()).title
        },
        deleteRow(d) {
            console.log(d)
            const id = d.id
            let self = this
            AjaxCommon(`/api/Dictionary/DeleteData/${id}`, 'post', {}).then((res) => {
                console.log(res, 'res...............')
                if (res?.data?.Code == 200) {
                    PopupCommon.notify('success', '删除成功')
                    self.initDownYzzd()
                } else {
                    const msg = res?.data?.Message
                    if (msg) {
                        PopupCommon.notify('error', msg)
                    }
                }
            })
        },
        deleteTableRow(d) {
            const id = d.type_tag
            let self = this
            AjaxCommon(`/api/Dictionary/DeleteType/${id}`, 'post', {}).then((res) => {
                if (res?.data?.Code == 200) {
                    PopupCommon.notify('success', '删除成功')
                    self.initPage()
                } else {
                    const msg = res?.data?.Message
                    if (msg) {
                        PopupCommon.notify('error', msg)
                    }
                }
            })
        },
        // 初始化事件
        initPage() {
            let self = this
            const params = `?PageSize=${this.pageSize}&PageIndex=${this.pageNo}`
            AjaxCommon(`/api/Dictionary/GetPageCodeTypeData${params}`, 'get', null).then((res) => {
                console.log(res, 'res...........')
                if (res?.data?.Code == 200) {
                    const data = res?.data.Message
                    console.log(data?.rows, 'data?.rows...')
                    self.dataSource = data?.rows
                    self.pageCount = parseInt(data?.total)
                } else {
                    PopupCommon.notify('error', res?.data?.msg)
                }
            })
        },
        initDownYzzd() {
            let self = this
            const params = `?PageSize=1000&PageIndex=${this.pageNoDown}&Type_tag=${this.tableItem.type_tag}`
            console.log(params, 'params......')
            AjaxCommon(`/api/Dictionary/GetCodePageData${params}`, 'get', null).then((res) => {
                console.log(res, 'res...........')
                if (res?.data?.Code == 200) {
                    const data = res?.data.Message
                    console.log(data?.rows, 'data?.rows...')
                    self.dataSourceDown = data?.rows
                    self.pageCountDown = parseInt(data?.total)
                } else {
                    PopupCommon.notify('error', res?.data?.msg ?? res?.data?.Message)
                }
            })
        }
    },
    mounted() {
        this.$nextTick(() => {
            this.getHeight()
            this.initPage()
        })

        /*窗口自适应，关键代码*/
        window.onresize = () => {
            this.getHeight()
        }
    }
}
</script>

<style scoped lang="scss">
.flexDict {
    display: block;
    .firstTableDict {
        .mcTableIndex {
            height: 350px;
        }
    }
}

.flexDict .flex-left {
    width: 350px;
    margin-right: 10px;
}

.flexDict .flex-right {
    flex: 1;
}

.flexDict .flex-left .navigationBar {
    height: 36px;
    line-height: 36px;
    background-color: #fff;
}

.flexDict .flex-left .flex-tree {
    background-color: #fff;
    margin-top: 10px;
    height: calc(100vh - 148px);
    overflow-y: auto;
}

.flexDict .flex-left .flex-tree .delete {
    color: red;
    float: right;
    margin-top: 9px;
    cursor: pointer;
}
.flexDict .flex-left .flex-tree .edit {
    color: blue;
    float: right;
    margin-top: 9px;
    cursor: pointer;
    margin-right: 10px;
}
.flexDict .flex-left .flex-tree .tree-item {
    height: 32px;
    line-height: 32px;
    margin: 5px 10px;
    padding: 0 10px;
    font-size: 14px;
    cursor: pointer;
}
.flexDict .flex-left .flex-tree .tree-item:hover {
    background-color: #e4f1fe;
}
.flexDict .flex-left .flex-tree .hover {
    background-color: #e4f1fe;
}

.flexDict .flex-left .navigationBar label {
    text-align: left;
    font-size: 16px;
    color: #333;
    margin-left: 10px;
}

.flexDict .flex-left .navigationBar span {
    float: right;
    margin-right: 10px;
    color: #333;
    cursor: pointer;
}

.singleTable {
    margin-bottom: 20px;
}
.singleBtn {
    position: absolute;
    bottom: 8px;
    right: 9px;
}

.select {
    font-size: 14px;
    line-height: 30px;
    padding: 5px 10px;
}

.select .item {
    display: inline-block;
    padding: 0px 10px;
    text-align: center;
    border: 1px solid #e0e0e0;
    border-radius: 4px;
    margin-right: 10px;
    margin-bottom: 10px;
}
.itemDiv {
    display: inline-block;
}
.selectMain {
    height: 515px;
}
.selectMain .selectLeft {
    width: 35%;
    float: left;
}

.selectMain .selectLeft .selectLeftWrapper {
    margin: 10px;
    border: 1px solid #ebeef5;
    padding: 10px;
    height: 478px;
    overflow-y: auto;
}

.selectMain .selectRight {
    width: 65%;
    float: left;
}
</style>
